package com.running.base.run.util;

import com.running.base.run.domain.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class SessionManager {
    // 存储在线用户会话
    private final ConcurrentHashMap<String, HttpSession> sessions = new ConcurrentHashMap<>();
    // 在线用户计数器
    private final AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 添加会话
     */
    public void addSession(HttpSession session) {
        String sessionId = session.getId();
        if (!sessions.containsKey(sessionId)) {
            sessions.put(sessionId, session);
            onlineCount.incrementAndGet();
        }
    }

    /**
     * 移除会话
     */
    public void removeSession(HttpSession session) {
        String sessionId = session.getId();
        if (sessions.remove(sessionId) != null) {
            onlineCount.decrementAndGet();
        }
    }

    /**
     * 获取在线用户数
     */
    public int getOnlineCount() {
        // 清理已过期的会话
        sessions.entrySet().removeIf(entry -> {
            try {
                return entry.getValue().getAttribute("user") == null;
            } catch (IllegalStateException e) {
                // 会话已失效
                return true;
            }
        });
        
        // 更新计数器
        onlineCount.set(sessions.size());
        
        return onlineCount.get();
    }

    /**
     * 获取所有在线会话
     */
    public ConcurrentHashMap<String, HttpSession> getSessions() {
        return sessions;
    }
}